package com.msb.api.filter.impl;

import com.msb.api.ApiStarterApp;
import com.msb.api.feign.BeaconCacheClient;
import com.msb.api.filter.CheckFilter;
import com.msb.api.filter.CheckFilterContext;
import com.msb.common.constart.ApiConstant;
import com.msb.common.constart.CacheConstant;
import com.msb.common.enums.ExceptionEnums;
import com.msb.common.exception.GraceException;
import com.msb.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: lmf
 * @Create: 2025/3/7 9:06
 * Description: 余额检查过滤器
 */
@Service("fee")
@Slf4j
public class FeeCheckFilter implements CheckFilter {
    @Resource
    private BeaconCacheClient cacheClient;

    @Override
    public void check(StandardSubmit submit) {
        //只要短信内容的文字长度小于等于70个字，按照一条计算
        int MAX_LENGTH = 70;
        // 如果短信内容的文字长度超过70，67字/条计算
        int LOOP_LENGTH = 67;
        // 余额字段
        String BALANCE = "balance";

        log.info("余额验证fee check");

        //1、从submit中获取到短信内容长度
        int length = submit.getText().length();
        //2、判断短信内容的长度，如果小于等于70，算作一条，如果大于70字，按照67字/条，算出来当前短信的费用

        if (length <= MAX_LENGTH) {
            submit.setFee(ApiConstant.SINGLE_FEE);
        } else {
            // LOOP_LENGTH 字按一条计算
            int strip = length % LOOP_LENGTH == 0 ? 1 : length / LOOP_LENGTH + 1;
            submit.setFee(ApiConstant.SINGLE_FEE * strip);

        }

        //3、从Redis中查询出客户剩余的金额
        long balance =
                ((Integer) cacheClient.hGet(CacheConstant.CLIENT_BALANCE + submit.getClientId(), BALANCE)).longValue();
        log.info("balance{}", balance);

        //4、判断金额是否满足当前短信费用
        if (balance >= submit.getFee()) {
            log.info("余额验证通过");
            return;
        }

        GraceException.display(ExceptionEnums.BALANCE_NOT_ENOUGH);
    }
}
